package cn.haocxy.jfm.gui;

import java.util.concurrent.atomic.AtomicInteger;

import javafx.stage.Stage;
import cn.haocxy.jfm.file.FilePath;
import cn.haocxy.jfm.filelist.FileList;

public class JfmWindow extends Stage {

	
	// 统计当前打开的JfmWindow的数量, 数量为0时退出程序
	private static final AtomicInteger counter = new AtomicInteger(0);
	
	public JfmWindow(String path) {
		setup(path, this);
	}
	
	public JfmWindow(FilePath path) {
		setup(path, this);
	}
	
	/**
	 * 在一个已有的stage上构造一个JfmWindow
	 * <p>
	 * 主要是防止{@code Application.start(Stage stage)}中的stage浪费
	 * @param path
	 * @param stage
	 * @return
	 */
	public static Stage setup(FilePath path, Stage stage) {
		FileList model = new FileList(path);
		JfmScene jfmScene = new JfmScene(model);
		stage.setScene(jfmScene.toScene());
		stage.setTitle(model.getCurrentDir().toString());
		
		model.getDirEventHandlers().addHandler(e->{
			stage.setTitle(model.getCurrentDir().toString());
		});
		
		stage.setOnShowing(e->{
			jfmScene.onShowing();
		});
		
		stage.setOnShown(e->counter.incrementAndGet());
		
		stage.setOnCloseRequest(e->{
			stage.hide();
			
			int num = counter.decrementAndGet();
			if (num == 0) {
				System.exit(0);
			}
		});

		return stage;
	}
	
	public static Stage setup(String path, Stage stage) {
		return setup(FilePath.fromString(path), stage);
	}
}
